package se.vgregion.icc.handlers;

import java.io.StringReader;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import se.riv.itintegration.monitoring.pingforconfigurationresponder.v1.PingForConfigurationResponseType;
import se.vgregion.icc.handlers.annotations.DependencyResponseHandler;

/***
 * Handler to process PingForConfigurationResponseType.
 * 
 * @author ricra2 & andan40
 * @see {@link se.vgregion.icc.handlers.ResponseHandler}
 * @see {@link se.riv.itintegration.monitoring.pingforconfigurationresponder.v1.PingForConfigurationResponseType}
 * @see {@link se.vgregion.icc.handlers.annotations.DependencyResponseHandler}
 */
@DependencyResponseHandler
public final class PingForConfigurationResponseTypeHandler implements ResponseHandler {
    private static final Logger LOG = LoggerFactory.getLogger(PingForConfigurationResponseTypeHandler.class);

    private static final String HANDLED_CLASS_TAG = "PingForConfigurationResponse";

    /***
     * {@inheritDoc}
     */
    @Override
    public Object unmarshal(String xmlToUnmarshal) {
        PingForConfigurationResponseType response = null;
        try {
            response = unmarshalXml(PingForConfigurationResponseType.class, xmlToUnmarshal);
        } catch (JAXBException e) {
            LOG.error("Couldn't unmarshal the xml String" + xmlToUnmarshal);
        }
        return response;
    }

    /***
     * Method to unmarshal xml.
     * 
     * @param clazz the class you want the xml to become
     * @param <T> expected return type
     * @param xml to unmarshal.
     * @return the class you put on the left side of the equals operator.
     * @throws JAXBException - If JAXB fails.
     */
    private static <T> T unmarshalXml(Class<T> clazz, String xml) throws JAXBException {
        JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

        @SuppressWarnings("unchecked")
        JAXBElement<T> unmarshal = (JAXBElement<T>) unmarshaller.unmarshal(new StringReader(xml));
        return unmarshal.getValue();
    }

    /***
     * {@inheritDoc}
     */
    @Override
    public String getHandledClassTagName() {
        return HANDLED_CLASS_TAG;
    }

}
